import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }

    public Runnable getTask() {
        return task;
    }

    public void setTask(Runnable task) {
        this.task = task;
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;
    }
}

class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>(100);
    private Object locker = new Object();

    public MyTimer() {
       Thread t = new Thread(() -> {
           while (true) {
               synchronized (locker) {
                   try {
                       while (queue.isEmpty()) {
                           locker.wait();
                       }
                       MyTimerTask task = queue.peek();
                       if (task.getTime() > System.currentTimeMillis()) {
                           locker.wait();
                       } else {
                           queue.poll().getTask().run();
                       }
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
           }
       });

       t.start();
    }

    public void schedule(Runnable task, long delay) {
        synchronized (locker) {
            MyTimerTask myTimerTask = new MyTimerTask(task, System.currentTimeMillis() + delay);
            queue.offer(myTimerTask);
            locker.notify();
        }
    }
}

public class Demo2 {
    public static void main(String[] args) {
        /*Timer timer = new Timer();
        for (int i = 0; i < 10; i++) {
            int id = i;
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("hello java" + id);
                }
            },1000);3
        }*/

        MyTimer timer = new MyTimer();

    }
}
